<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="css/base.css">
  <script src="https://s4.ssl.qhres.com/!928fb688/spritejs.min.js"></script>
  <style>
    html, body {
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
      overflow: hidden;
    }
    canvas {
      border: solid 1px;
      box-sizing: border-box;
    }
    #scene-container {
      width: 100%;
      height: 100%;
    }
    #box-rect-demo {
      position: absolute;
      padding: 20px 0 0 20px;
      top: 0;
    }
  </style>
</head>
<body>
  <div id="scene-container"></div>
  <script>
  const {Scene, Sprite} = spritejs
  const scene = new Scene('#scene-container', {
    viewport: ['auto', 'auto'],
    resolution: [1540, 600],
    stickMode: 'width',
  })
  const layer = scene.layer('fglayer')
  let zIndex = 1

  function draggable(sprite) {
    if(sprite.isDraggable) return

    sprite.isDraggable = true

    let x0,
      y0,
      startPos

    function onMouseMove(evt) {
      const dx = evt.x - x0,
        dy = evt.y - y0

      sprite.attr('pos', [startPos[0] + dx, startPos[1] + dy])
      evt.stopDispatch()
    }

    sprite.on('mousedown', (evt) => {
      x0 = evt.x
      y0 = evt.y
      startPos = sprite.attr('pos')
      sprite.attr('zIndex', zIndex++)
      layer.on('mousemove', onMouseMove)
      evt.stopDispatch()
    })

    sprite.on('mousemove', (evt) => {
      evt.stopDispatch()
    })
    sprite.on('mouseenter', (evt) => {
      sprite.attr({border: [4, '#000']})
    }).on('mouseleave', (evt) => {
      sprite.attr({border: 0})
    })

    document.documentElement.addEventListener('mouseup', () => {
      layer.off('mousemove', onMouseMove)
    })

    return sprite
  }

  const s1 = new Sprite()
  s1.attr({
    anchor: [0.5, 0.5],
    pos: [770, 300],
    size: [200, 200],
    rotate: 45,
    bgcolor: '#3c7',
  })

  const s2 = new Sprite()
  s2.attr({
    anchor: [0.5, 0.5],
    pos: [270, 300],
    size: [200, 200],
    bgcolor: '#c37',
  })

  const s3 = new Sprite()
  s3.attr({
    anchor: [0.5, 0.5],
    pos: [1270, 300],
    size: [200, 200],
    bgcolor: '#73c',
  })


  layer.append(...[s1, s2, s3].map(draggable))

  layer.on('mousemove', (evt) => {
    if(evt.targetSprites.some(target => target.isDraggable)) {
      scene.container.style.cursor = 'move'
    } else {
      scene.container.style.cursor = 'default'
    }
  })
  </script>
</body>
</html>
